package com.gome.ocean.controller.synchrodata;

import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.client.methods.HttpGet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.gome.ocean.common.constants.SynchroDataContants;
import com.gome.ocean.common.enums.CangoRspStatus;
import com.gome.ocean.common.exception.BaseControllerException;
import com.gome.ocean.common.utils.ResponsePage;
import com.gome.ocean.dao.model.cango.CangoInstances;
import com.gome.ocean.dao.model.cango.CangoResponseVO;
import com.gome.ocean.dao.model.cango.ParamsVO;
import com.gome.ocean.service.base.AuthorityBaseController;
import com.gome.ocean.service.cangologicservice.ICangoLogicService;
import com.google.common.collect.Maps;

/**
 * @author zhangguoqing 2017年2月17日 下午3:19:44
 * @since 5.0.0 用于httpClient调取ocean-server中url 多任务执行
 */
@RestController
@RequestMapping("/synchroData")
public class SynchroOnlineCopyDataController extends AuthorityBaseController {

    private static final Logger LOG  = LoggerFactory.getLogger(SynchroOnlineCopyDataController.class);
    private static final String PORT = "8082";

    @Autowired
    private ICangoLogicService iCangoLogicService;

    @RequestMapping("/getDataTaskPage")
    public ModelAndView saveSyncCopyDataTask(HttpServletRequest request, ModelAndView mav) {
        try {
            mav.addObject("projectNames", getProperProjects());
        } catch (BaseControllerException e) {
            LOG.error(e.getMessage(), e);
            mav.addObject("errorMsg", ERROR_MSG);
        }
        mav.setViewName("synchrodata/insert_page");
        return mav;
    }

    /**
     * 如果源类型为mysql，则用cango.若源类型为oracle，模式为yugong迁移。
     */
    @RequestMapping("/ajaxCommitSaveTask")
    public CangoResponseVO ajaxCommitSaveTask(HttpServletRequest request) {
        String optType = request.getParameter("option");
        String instanceName = String.valueOf(new Date().getTime()).concat("-" + new Random().nextInt(1000));// 唯一使用的实例名称
        String sourceTableName = request.getParameter("sourceTableName");
        String targetTableName = request.getParameter("targetTableName");
        String projectName = request.getParameter("projectName");
        String sourceId = request.getParameter("sourceDataSourceId");
        String targetId = request.getParameter("targetDataSourceId");
        String isRockmq = request.getParameter("isRocketMqTarget");
        String topicName = StringUtils.isBlank(request.getParameter("topicName")) ? "" : request
            .getParameter("topicName");
        String nameSrvAddr = StringUtils.isBlank(request.getParameter("nameSrvAddr")) ? "" : request
            .getParameter("nameSrvAddr");
        String moveMode = StringUtils.isBlank(request.getParameter("moveMode")) ? "0" : request
            .getParameter("moveMode");
        ParamsVO paramsVO = new ParamsVO();
        paramsVO.setInstanceName(instanceName);
        paramsVO.setIsRocketmq(Integer.parseInt(isRockmq));
        paramsVO.setNameSrvAddr(nameSrvAddr);
        paramsVO.setProjectName(projectName);
        paramsVO.setSourceId(Long.parseLong(sourceId));
        paramsVO.setSourceTableName(sourceTableName);
        paramsVO.setTargetTableName(targetTableName);
        paramsVO.setTargetId(Long.parseLong(targetId));
        paramsVO.setTopicName(topicName);
        paramsVO.setMoveMode(Integer.parseInt(moveMode));
        String params = JSON.toJSONString(paramsVO);

        CangoResponseVO ponseVO = new CangoResponseVO();
        String path = "";
        try {
            if (optType.equalsIgnoreCase("create")) {
                path = SynchroDataContants.getHttpSyncDataIpAddsStr(this.getDiffEnvOceanIp().concat(":").concat(PORT),
                    "add",
                    URLEncoder.encode(params, "UTF-8"));
            } else {
                path = SynchroDataContants.getHttpSyncDataIpAddsStr(this.getDiffEnvOceanIp().concat(":").concat(PORT),
                    "updateInce",
                    URLEncoder.encode(params, "UTF-8"));
            }
            HttpGet httpGet = getHttpGet(path);
            ponseVO = parseResponse(httpGet);
        } catch (Exception e) {
            LOG.error(ExceptionUtils.getMessage(e));
            ponseVO.setFailMsg(ExceptionUtils.getMessage(e));
            ponseVO.setStatus(CangoRspStatus.FAILURE);
        }
        return ponseVO;
    }

    @RequestMapping("/findAllSyncCopyDataTask")
    public ModelAndView findAllSyncCopyDataTask(HttpServletRequest request, ModelAndView mav) {
        try {
            mav.addObject("projectNames", getProperProjects());
        } catch (BaseControllerException e) {
            LOG.error(e.getMessage(), e);
            mav.addObject("errorMsg", ERROR_MSG);
        }
        mav.setViewName("synchrodata/find_page");
        return mav;
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping("/findAllBean")
    public ResponsePage findAllBean(HttpServletRequest request) {
        ResponsePage response = getResponsePage();
        Integer pageNum = getPageNum();
        Integer pageSize = getPageSize();
        try {
            Page<CangoInstances> cangoIncePage;
            if (isAdmin()) {
                cangoIncePage = (Page<CangoInstances>) iCangoLogicService.getAllBeanLists(pageNum, pageSize);
            } else {
                cangoIncePage = (Page<CangoInstances>) iCangoLogicService.getAllBeanListsByProjectNames(pageNum,
                    pageSize,
                    getCurrentUserProjects());
            }
            if (CollectionUtils.isEmpty(cangoIncePage)) return response.emptyPage(FIND_NO_RESULTS);
            return response.setPage(cangoIncePage, FIND_SUCCESS);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return response.setErrorMsg(EXCEPTION_MSG);
        }
    }

    @RequestMapping("/getSinglePage")
    public ResponsePage getSinglePageByName(HttpServletRequest request) {
        ResponsePage page = getResponsePage();
        String instanceName = request.getParameter("instanceName");
        CangoInstances cangoInce = iCangoLogicService.getBeanByInstanceName(instanceName);
        return page.setSingleObject(cangoInce, "查询成功");
    }

    @RequestMapping("/ajaxStartInstance")
    public CangoResponseVO ajaxStartInstance(HttpServletRequest request) {
        String instanceName = request.getParameter("instanceName");
        Long id = Long.parseLong(request.getParameter("id"));
        Map<String, Object> map = Maps.newHashMap();
        map.put("instanceName", instanceName);
        map.put("id", id);
        CangoResponseVO responseVO = new CangoResponseVO();
        try {
            String path = SynchroDataContants.getHttpSyncDataIpAddsStr(
                this.getDiffEnvOceanIp().concat(":").concat(PORT),
                "start",
                URLEncoder.encode(JSON.toJSONString(map), "UTF-8"));
            HttpGet httpGet = getHttpGet(path);
            responseVO = parseResponse(httpGet);
        } catch (Exception e) {
            LOG.error(ExceptionUtils.getMessage(e));
            responseVO.setFailMsg(ExceptionUtils.getMessage(e));
            responseVO.setStatus(CangoRspStatus.FAILURE);
        }
        return responseVO;
    }

    @RequestMapping("/ajaxStopIntance")
    public CangoResponseVO ajaxStopInstance(HttpServletRequest request) {
        String instanceName = request.getParameter("instanceName");
        Map<String, Object> map = Maps.newHashMap();
        map.put("instanceName", instanceName);
        CangoResponseVO responseVO = new CangoResponseVO();
        try {
            String path = SynchroDataContants.getHttpSyncDataIpAddsStr(
                this.getDiffEnvOceanIp().concat(":").concat(PORT),
                "stop",
                URLEncoder.encode(JSON.toJSONString(map), "UTF-8"));
            HttpGet httpGet = getHttpGet(path);
            responseVO = parseResponse(httpGet);
        } catch (Exception e) {
            LOG.error(ExceptionUtils.getMessage(e));
            responseVO.setFailMsg(ExceptionUtils.getMessage(e));
            responseVO.setStatus(CangoRspStatus.FAILURE);
        }
        return responseVO;
    }

    @RequestMapping("/deleteInstance")
    public CangoResponseVO deleteInstance(HttpServletRequest request) {
        CangoResponseVO responseVO = new CangoResponseVO();
        Map<String, Object> map = Maps.newHashMap();
        String instanceName = request.getParameter("instanceName");
        map.put("instanceName", instanceName);
        try {
            String path = SynchroDataContants.getHttpSyncDataIpAddsStr(
                this.getDiffEnvOceanIp().concat(":").concat(PORT),
                "deleteSleInce",
                URLEncoder.encode(JSON.toJSONString(map), "UTF-8"));
            HttpGet httpGet = getHttpGet(path);
            responseVO = parseResponse(httpGet);
        } catch (Exception e) {
            LOG.error(ExceptionUtils.getMessage(e));
            responseVO.setStatus(CangoRspStatus.FAILURE);
            responseVO.setFailMsg(ExceptionUtils.getMessage(e));
        }
        return responseVO;
    }

    @RequestMapping("/updateTask")
    public ModelAndView updateTask(ModelAndView mav) {
        try {
            mav.addObject("projectNames", getProperProjects());
        } catch (Exception e) {
            LOG.error(ExceptionUtils.getMessage(e));
        }
        mav.setViewName("synchrodata/update-page");
        return mav;
    }

    @RequestMapping("/startAllInce")
    public CangoResponseVO startAllInce() {
        CangoResponseVO responseVO = new CangoResponseVO();
        try {
            String path = SynchroDataContants
                .getHttpSyncDataIpAddsStr(this.getDiffEnvOceanIp().concat(":").concat(PORT), "startAll", "");
            HttpGet httpGet = getHttpGet(path);
            responseVO = parseResponse(httpGet);
        } catch (Exception e) {
            LOG.error(ExceptionUtils.getMessage(e));
            responseVO.setStatus(CangoRspStatus.FAILURE);
            responseVO.setFailMsg(ExceptionUtils.getMessage(e));
        }
        return responseVO;
    }

    @RequestMapping("/stopAllInce")
    public CangoResponseVO stopAllInce() {
        CangoResponseVO responseVO = new CangoResponseVO();
        try {
            String path = SynchroDataContants
                .getHttpSyncDataIpAddsStr(this.getDiffEnvOceanIp().concat(":").concat(PORT), "stopAll", "");
            HttpGet httpGet = getHttpGet(path);
            responseVO = parseResponse(httpGet);
        } catch (Exception e) {
            LOG.error(ExceptionUtils.getMessage(e));
            responseVO.setStatus(CangoRspStatus.FAILURE);
            responseVO.setFailMsg(ExceptionUtils.getMessage(e));
        }
        return responseVO;
    }

    @RequestMapping("/clearAllInce")
    public CangoResponseVO clearAllInce() {
        CangoResponseVO responseVO = new CangoResponseVO();
        try {
            String path = SynchroDataContants
                .getHttpSyncDataIpAddsStr(this.getDiffEnvOceanIp().concat(":").concat(PORT), "clearAll", "");
            HttpGet httpGet = getHttpGet(path);
            responseVO = parseResponse(httpGet);
        } catch (Exception e) {
            LOG.error(ExceptionUtils.getMessage(e));
            responseVO.setStatus(CangoRspStatus.FAILURE);
            responseVO.setFailMsg(ExceptionUtils.getMessage(e));
        }
        return responseVO;
    }

    // 启动实例
    @RequestMapping("/enableInce")
    public CangoResponseVO enableInce(HttpServletRequest request) {
        String instanceName = request.getParameter("instanceName");
        Map<String, Object> map = Maps.newHashMap();
        map.put("instanceName", instanceName);
        CangoResponseVO responseVO = new CangoResponseVO();
        try {
            String path = SynchroDataContants.getHttpSyncDataIpAddsStr(
                this.getDiffEnvOceanIp().concat(":").concat(PORT),
                "enable",
                URLEncoder.encode(JSON.toJSONString(map), "UTF-8"));
            HttpGet httpGet = getHttpGet(path);
            responseVO = parseResponse(httpGet);
        } catch (Exception e) {
            LOG.error(ExceptionUtils.getMessage(e));
            responseVO.setStatus(CangoRspStatus.FAILURE);
            responseVO.setFailMsg(ExceptionUtils.getMessage(e));
        }
        return responseVO;
    }

    // 禁用实例
    @RequestMapping("/disableInce")
    public CangoResponseVO disableInce(HttpServletRequest request) {
        String instanceName = request.getParameter("instanceName");
        Map<String, Object> map = Maps.newHashMap();
        map.put("instanceName", instanceName);
        CangoResponseVO responseVO = new CangoResponseVO();
        try {
            String path = SynchroDataContants.getHttpSyncDataIpAddsStr(
                this.getDiffEnvOceanIp().concat(":").concat(PORT),
                "disable",
                URLEncoder.encode(JSON.toJSONString(map), "UTF-8"));
            HttpGet httpGet = getHttpGet(path);
            responseVO = parseResponse(httpGet);
        } catch (Exception e) {
            LOG.error(ExceptionUtils.getMessage(e));
            responseVO.setStatus(CangoRspStatus.FAILURE);
            responseVO.setFailMsg(ExceptionUtils.getMessage(e));
        }
        return responseVO;
    }
}
